package com.qlyl.modules.information.ethadapter;


import com.senlin.ethereum.common.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 把完成的交易hash存入redis等待验证
 *
 * @author huwei
 */
@Component
public class EthRedisCache {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public Long putTransactionHash(String hash) {
        return redisTemplate.opsForList().rightPush(EthConst.REDIS_TRANSACTION_HASH_LIST, hash);
    }

    public String popTransactionHash() {
        return redisTemplate.opsForList().leftPop(EthConst.REDIS_TRANSACTION_HASH_LIST,3, TimeUnit.SECONDS);
    }

    public Long min(long limit) {
        long size = redisTemplate.opsForList().size(EthConst.REDIS_TRANSACTION_HASH_LIST);
        return size > limit ? limit : size;
    }

    public List<String> popsTransactionHash(long limit) {
        final long size = this.min(limit);
        if (size <= 0) return null;

        List<Object> lis = redisTemplate.executePipelined(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
                redisConnection.openPipeline();
                for (int i = 0; i < size; i ++) {
                    redisConnection.lPop(EthConst.REDIS_TRANSACTION_HASH_LIST.getBytes());
                }
                return null;
            }
        });

        if (lis != null && lis.size() > 0)
            return lis.stream().map(s -> (String) s).collect(Collectors.toList());
        return null;
    }
}
